package com.leyou.auth.config;

import com.leyou.auth.client.AuthClient;
import com.leyou.auth.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 虎哥
 */
@Slf4j
@EnableConfigurationProperties(ClientProperties.class)
@Configuration
@ConditionalOnProperty(prefix = "ly.auth", name = {"clientId", "secret"})
public class JwtConfig {

    @Autowired
    private AuthClient authClient;

    @Bean
    public JwtUtils jwtUtils(ClientProperties prop) {
        String key;
        while (true) {
            // 获取秘钥
            try {
                key = authClient.getJwtKey(prop.getClientId(), prop.getSecret());
                if (StringUtils.isBlank(key)) {
                    throw new RuntimeException("秘钥为空");
                }
                log.info("秘钥加载成功");
                break;
            } catch (Exception e) {
                log.error("秘钥加载失败，10秒后重试", e);
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e2) {
                    throw new RuntimeException(e2);
                }
            }

        }
        // 创建JwtUtils
        return new JwtUtils(key);
    }
}
